package aplug.data.db;

import javax.inject.Inject;
import javax.inject.Singleton;

import aplug.data.db.model.CarData;
import aplug.data.db.model.CarDataDao;
import aplug.data.db.model.DaoMaster;
import aplug.data.db.model.DaoSession;
import io.reactivex.Observable;

/**
 * 车辆信息
 * Created by kelly on 2017/7/22.
 */

@Singleton
public class AppDbHelper implements DbHelper {

    private final DaoSession daoSession;

    @Inject
    public AppDbHelper(DbOpenHelper dbOpenHelper) {
        this.daoSession = new DaoMaster(dbOpenHelper.getWritableDb()).newSession();
    }

    /**
     * 增加设置
     *
     * @param carData
     * @return
     */
    @Override
    public Observable<Boolean> insertCar(CarData carData) {
        return Observable.fromCallable(() -> {
            daoSession.getCarDataDao().insertOrReplace(carData);
            return true;
        });
    }

    /**
     * 修改设置
     *
     * @param carData
     * @return
     */
    @Override
    public Observable<Boolean> modifyCar(CarData carData) {
        return Observable.fromCallable(() -> {
            daoSession.getCarDataDao().update(carData);
            return true;
        });
    }

    /**
     * 根据id查询唯一的车辆信息
     *
     * @param id
     * @return
     */
    @Override
    public Observable<CarData> getCar(long id) {
        return Observable.fromCallable(() -> {
            CarData carData = daoSession.getCarDataDao().queryBuilder()
                    .where(CarDataDao.Properties.Id.eq(id)).build().unique();
            if (carData == null) {
                throw new IllegalStateException();
            } else
                return carData;
        });
    }
}
